package com.weiqk.pmdemo.service.impl;

import com.weiqk.pmdemo.dao.PurchaseLinkRespository;
import com.weiqk.pmdemo.dao.PurchaseRepository;
import com.weiqk.pmdemo.dto.ApplyLinkDto;
import com.weiqk.pmdemo.dto.PurchaseLinkDto;
import com.weiqk.pmdemo.dto.PurchaseLinkInDto;
import com.weiqk.pmdemo.pojo.ApplyLink;
import com.weiqk.pmdemo.pojo.PayLink;
import com.weiqk.pmdemo.pojo.Purchase;
import com.weiqk.pmdemo.pojo.PurchaseLink;
import com.weiqk.pmdemo.service.PayLinkService;
import com.weiqk.pmdemo.service.PurchaseLinkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class PurchaseLinkServiceImpl implements PurchaseLinkService {
    @Autowired
    PurchaseLinkRespository purchaseLinkRespository;
    @Autowired
    DicServiceImpl dicService;
    @Autowired
    PurchaseRepository purchaseRepository;
    @Override
    public List<PurchaseLinkDto> findAll() {
        Iterable<PurchaseLink> all = purchaseLinkRespository.findAll();
        List<PurchaseLinkDto> purchaseLinkDtos = new ArrayList<>();
        for ( PurchaseLink a:all){
            int materialCode = a.getMaterialCode();
            String materialName = dicService.findMaterialNameByDicCode(materialCode);
            PurchaseLinkDto pld= new PurchaseLinkDto();
            pld.setPurchaseLink(a);
            pld.setMaterialName(materialName);
            purchaseLinkDtos.add(pld);
        }
        return purchaseLinkDtos;
    }

    @Override
    public Boolean deleteById(int id) {
        purchaseLinkRespository.deleteById(id);
        return true;
    }

    @Override
    public Boolean update(PurchaseLinkInDto purchaseLinkInDto) {
        //处理时间
        PurchaseLink purchaseLink = purchaseLinkInDto.getPurchaseLink();
        purchaseLink.setUpadteTime(new Date());
        //处理外键数据
        int purchaseNum = purchaseLinkInDto.getPurchaseNum();
        Purchase purchase = purchaseRepository.findOne(purchaseNum);
        purchaseLink.setPurchase(purchase);

        //操作数据库
        purchaseLinkRespository.save(purchaseLink);
        return true;
    }

    @Override
    public Boolean put(PurchaseLinkInDto purchaseLinkInDto) {
        //处理时间
        PurchaseLink purchaseLink = purchaseLinkInDto.getPurchaseLink();
        purchaseLink.setUpadteTime(new Date());
        purchaseLink.setCreateTime(new Date());
        //处理外键数据
        int purchaseNum = purchaseLinkInDto.getPurchaseNum();
        Purchase purchase = purchaseRepository.findOne(purchaseNum);
        purchaseLink.setPurchase(purchase);
        //操作数据库
        purchaseLinkRespository.save(purchaseLink);
        return true;
    }

    @Override
    public int countWithPurchaseId(int id) {
        List<PurchaseLink> purchaseLinks = purchaseLinkRespository.countPLinkByP(id);
        return purchaseLinks.size();

    }


}
